<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/5/20
 * Time: 16:16
 */
namespace app\admin\controller;
use app\models\Models;
use app\validate\AdminValidate;
use think\Config;
use think\Cookie;
use think\Request;

/**
 * +----------------------------------------------
 * Class Login
 * @package app\admin\controller
 * 管理员登录类
 * +----------------------------------------------
 */
class Login extends Base{
    /**
     * 后台登录
     * @return array|\think\response\View
     */
    public function login(){
        if(request()->isPost()){
            $post  = input('param.');
            $admin = new Models('admin');
            try{
                // 登录场景验证
                $validate = $this->validate($post,'Admin.login');
                if(true !== $validate){
                    throw new \LogicException($validate,1000);
                }

                $info = $admin->_find(['username'=>$post['username']]);
                $info['remember'] = $post['remember'];
                // 验证用户状态
                if($info['status'] == $admin::STATUS_OFF){
                    throw new \LogicException('账号已锁定',1002);
                }
                if($info['status'] == $admin::STATUS_NOT_ACTIVE){
                    throw new \LogicException('账号未认证',1002);
                }

                // 验证密码
                $bool = password_verify($post['password'],$info['password']);
                if(!$bool){
                    throw new \LogicException('登录失败',1001);
                }

                // 登录后置操作
                self::afterLogin($info);
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $config = new Models('config');
        $config['site_name'] = $config->getValue(['key' => 'site_name'],'value');
        $config['copyright'] = $config->getValue(['key' => 'copyright'],'value');
        return view('login',['config'=>$config]);
    }

    /**
     * 登录后置操作
     * @param $info
     */
    protected function afterLogin($info){
        $admin = new Models('admin');
        // 更新用户登陆信息
        $save['id']              = $info['id'];
        $save['last_login_time'] = time();
        $save['last_login_ip']   = ip2long($_SERVER["REMOTE_ADDR"]);
        $save['login_times']     = ['exp','login_times+1'];
        $bool = $admin->_save($save);
        if(!$bool){
            throw new \LogicException('登录失败',1001);
        }
        // 记录cookie
        cookie('join_login',null);
        $info['remember'] == 1 ? cookie('join_login',$info['id'],3600 * 24 * 7) : cookie('join_login',$info['id'],3600);
        // 添加操作日志
        self::addLog('登录');
    }

    /**
     * 退出
     * */
    public function logout(){
        cookie('join_login',null);
        $this->redirect('login/login');
    }
}